<template>
  <el-container class="wrapper">
    <el-header class="header">管理员登录</el-header>
    <el-main>
      <el-form :model="loginForm" :rules="loginFormRules" label-position="right" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%" type="primary" @click="submit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import sha256 from "js-sha256";

export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == null)
        callback(new Error("请输入用户名"));
      const re = /^[A-Za-z_]+$/;
      if (re.test(value))
        callback();
      callback(new Error("用户名需由英文字母或下划线组成"))
    }
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginFormRules: {
        username: [
          {required: true, type: "string", message: "请输入用户名", trigger: 'blur'},
          {min: 4, max: 12, message: "用户名长度需介于4至12个字符", trigger: 'blur'},
          {validator: validateUsername, trigger: 'blur'},
        ],
        password: [
          {required: true, type: "string", message: "请输入密码", trigger: 'blur'},
          {min: 6, max: 12, message: "密码长度需介于6至12个字符", trigger: 'blur'},
        ],
      }
    };
  },
  methods: {
    submit: function () {
      this.$axios.post("/api/admin/login", {
        name: this.loginForm.username,
        // password: sha256(this.loginForm.password)
        password: this.loginForm.password
      })
        .then(res => {
          const code = res.data.statusCode;
          const waitTime = 2;
          if (code === 200) {
            this.$message.success(`登录成功，界面将在${waitTime}秒后自动跳转。`);
            const redirect = this.$route.query.redirect || "/";
            setTimeout(() => {
              this.$router.push(redirect.toString());
            }, waitTime * 1000);
          } else if (code === 401) {
            this.$message.error("该账号为普通用户，无权限登录！");
          } else if (code === 403) {
            this.$message.error("用户名和密码不匹配！");
          } else if (code === 404) {
            this.$message.error("用户名不存在！");
          } else {
            this.$message.error("未知错误！");
          }
        });
    }
  },
}
</script>

<style scoped>

.wrapper {
  text-align: center;
  width: 25%;
  max-width: 600px;
  min-width: 400px;
  margin: 15vh auto auto;
}

.header {
  font-size: 20px;
  font-weight: bold;
}

</style>